{
  "cells": [
    {
      "cell_type": "raw",
      "id": "10238e62-3465-4973-9279-606cbb7ccf16",
      "metadata": {
        "vscode": {
          "languageId": "raw"
        }
      },
      "source": [
        "---\n",
        "sidebar_label: DuckDuckGoSearch\n",
        "---"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a6f91f20",
      "metadata": {},
      "source": [
        "# DuckDuckGoSearch\n",
        "\n",
        "This notebook provides a quick overview for getting started with [DuckDuckGoSearch](/docs/integrations/tools/). For detailed documentation of all DuckDuckGoSearch features and configurations head to the [API reference](https://api.js.langchain.com/classes/langchain_community_tools_duckduckgo_search.DuckDuckGoSearch.html).\n",
        "\n",
        "DuckDuckGoSearch offers a privacy-focused search API designed for LLM Agents. It provides seamless integration with a wide range of data sources, prioritizing user privacy and relevant search results.\n",
        "\n",
        "## Overview\n",
        "\n",
        "### Integration details\n",
        "\n",
        "| Class | Package | [PY support](https://python.langchain.com/docs/integrations/tools/ddg/) | Package latest |\n",
        "| :--- | :--- | :---: | :---: |\n",
        "| [DuckDuckGoSearch](https://api.js.langchain.com/classes/langchain_community_tools_duckduckgo_search.DuckDuckGoSearch.html) | [`@langchain/community`](https://www.npmjs.com/package/@langchain/community) | ✅ |  ![NPM - Version](https://img.shields.io/npm/v/@langchain/community?style=flat-square&label=%20&) |\n",
        "\n",
        "## Setup\n",
        "\n",
        "The integration lives in the `@langchain/community` package, along with the `duck-duck-scrape` dependency:\n",
        "\n",
        "```{=mdx}\n",
        "import IntegrationInstallTooltip from \"@mdx_components/integration_install_tooltip.mdx\";\n",
        "import Npm2Yarn from \"@theme/Npm2Yarn\";\n",
        "\n",
        "<IntegrationInstallTooltip></IntegrationInstallTooltip>\n",
        "\n",
        "<Npm2Yarn>\n",
        "  @langchain/community @langchain/core duck-duck-scrape\n",
        "</Npm2Yarn>\n",
        "```\n",
        "\n",
        "### Credentials\n",
        "\n",
        "It's also helpful (but not needed) to set up [LangSmith](https://smith.langchain.com/) for best-in-class observability:\n",
        "\n",
        "```typescript\n",
        "process.env.LANGSMITH_TRACING=\"true\"\n",
        "process.env.LANGSMITH_API_KEY=\"your-api-key\"\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "1c97218f-f366-479d-8bf7-fe9f2f6df73f",
      "metadata": {},
      "source": [
        "## Instantiation\n",
        "\n",
        "You can instantiate an instance of the `DuckDuckGoSearch` tool like this:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "8b3ddfe9-ca79-494c-a7ab-1f56d9407a64",
      "metadata": {},
      "outputs": [],
      "source": [
        "import { DuckDuckGoSearch } from \"@langchain/community/tools/duckduckgo_search\"\n",
        "\n",
        "const tool = new DuckDuckGoSearch({ maxResults: 1 })"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "74147a1a",
      "metadata": {},
      "source": [
        "## Invocation\n",
        "\n",
        "### [Invoke directly with args](/docs/concepts/tools)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "65310a8b-eb0c-4d9e-a618-4f4abe2414fc",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[{\"title\":\"San Francisco, CA Current Weather | AccuWeather\",\"link\":\"https://www.accuweather.com/en/us/san-francisco/94103/current-weather/347629\",\"snippet\":\"<b>Current</b> <b>weather</b> <b>in</b> San Francisco, CA. Check <b>current</b> conditions in San Francisco, CA with radar, hourly, and more.\"}]\n"
          ]
        }
      ],
      "source": [
        "await tool.invoke(\"what is the current weather in sf?\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d6e73897",
      "metadata": {},
      "source": [
        "### [Invoke with ToolCall](/docs/concepts/tools)\n",
        "\n",
        "We can also invoke the tool with a model-generated `ToolCall`, in which case a `ToolMessage` will be returned:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "f90e33a7",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "ToolMessage {\n",
            "  \"content\": \"[{\\\"title\\\":\\\"San Francisco, CA Weather Conditions | Weather Underground\\\",\\\"link\\\":\\\"https://www.wunderground.com/weather/us/ca/san-francisco\\\",\\\"snippet\\\":\\\"San Francisco <b>Weather</b> Forecasts. <b>Weather</b> Underground provides local & long-range <b>weather</b> forecasts, weatherreports, maps & tropical <b>weather</b> conditions for the San Francisco area.\\\"}]\",\n",
            "  \"name\": \"duckduckgo-search\",\n",
            "  \"additional_kwargs\": {},\n",
            "  \"response_metadata\": {},\n",
            "  \"tool_call_id\": \"tool_call_id\"\n",
            "}\n"
          ]
        }
      ],
      "source": [
        "// This is usually generated by a model, but we'll create a tool call directly for demo purposes.\n",
        "const modelGeneratedToolCall = {\n",
        "  args: {\n",
        "    input: \"what is the current weather in sf?\"\n",
        "  },\n",
        "  id: \"tool_call_id\",\n",
        "  name: tool.name,\n",
        "  type: \"tool_call\",\n",
        "}\n",
        "await tool.invoke(modelGeneratedToolCall)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "659f9fbd-6fcf-445f-aa8c-72d8e60154bd",
      "metadata": {},
      "source": [
        "## Chaining\n",
        "\n",
        "We can use our tool in a chain by first binding it to a [tool-calling model](/docs/how_to/tool_calling/) and then calling it:\n",
        "\n",
        "```{=mdx}\n",
        "import ChatModelTabs from \"@theme/ChatModelTabs\";\n",
        "\n",
        "<ChatModelTabs customVarName=\"llm\" />\n",
        "```\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "af3123ad-7a02-40e5-b58e-7d56e23e5830",
      "metadata": {},
      "outputs": [],
      "source": [
        "// @lc-docs-hide-cell\n",
        "\n",
        "import { ChatOpenAI } from \"@langchain/openai\"\n",
        "\n",
        "const llm = new ChatOpenAI({\n",
        "  model: \"gpt-4o-mini\",\n",
        "})"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "id": "fdbf35b5-3aaf-4947-9ec6-48c21533fb95",
      "metadata": {},
      "outputs": [],
      "source": [
        "import { HumanMessage } from \"@langchain/core/messages\";\n",
        "import { ChatPromptTemplate } from \"@langchain/core/prompts\";\n",
        "import { RunnableLambda } from \"@langchain/core/runnables\";\n",
        "\n",
        "const prompt = ChatPromptTemplate.fromMessages(\n",
        "  [\n",
        "    [\"system\", \"You are a helpful assistant.\"],\n",
        "    [\"placeholder\", \"{messages}\"],\n",
        "  ]\n",
        ")\n",
        "\n",
        "const llmWithTools = llm.bindTools([tool]);\n",
        "\n",
        "const chain = prompt.pipe(llmWithTools);\n",
        "\n",
        "const toolChain = RunnableLambda.from(\n",
        "  async (userInput: string, config) => {\n",
        "    const humanMessage = new HumanMessage(userInput,);\n",
        "    const aiMsg = await chain.invoke({\n",
        "      messages: [new HumanMessage(userInput)],\n",
        "    }, config);\n",
        "    const toolMsgs = await tool.batch(aiMsg.tool_calls, config);\n",
        "    return chain.invoke({\n",
        "      messages: [humanMessage, aiMsg, ...toolMsgs],\n",
        "    }, config);\n",
        "  }\n",
        ");\n",
        "\n",
        "const toolChainResult = await toolChain.invoke(\"how many people have climbed mount everest?\");"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "id": "28448fe2",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "AIMessage {\n",
            "  \"tool_calls\": [],\n",
            "  \"content\": \"As of December 2023, a total of 6,664 different people have reached the summit of Mount Everest.\"\n",
            "}\n"
          ]
        }
      ],
      "source": [
        "const { tool_calls, content } = toolChainResult;\n",
        "\n",
        "console.log(\"AIMessage\", JSON.stringify({\n",
        "  tool_calls,\n",
        "  content,\n",
        "}, null, 2));"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "570f4662",
      "metadata": {},
      "source": [
        "## Agents\n",
        "\n",
        "For guides on how to use LangChain tools in agents, see the [LangGraph.js](https://langchain-ai.github.io/langgraphjs/) docs."
      ]
    },
    {
      "cell_type": "markdown",
      "id": "4ac8146c",
      "metadata": {},
      "source": [
        "## API reference\n",
        "\n",
        "For detailed documentation of all DuckDuckGoSearch features and configurations head to the [API reference](https://api.js.langchain.com/classes/langchain_community_tools_duckduckgo_search.DuckDuckGoSearch.html)"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "TypeScript",
      "language": "typescript",
      "name": "tslab"
    },
    "language_info": {
      "codemirror_mode": {
        "mode": "typescript",
        "name": "javascript",
        "typescript": true
      },
      "file_extension": ".ts",
      "mimetype": "text/typescript",
      "name": "typescript",
      "version": "3.7.2"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
